import axios from 'axios'
import type { AxiosInstance } from 'axios'
import type { HYRequestConfig } from './type'
import type { ContentType } from '../config/index'
import type { LoadingInstance } from 'element-plus/lib/components/loading/src/loading'
import Router from '@/router'

import { ElLoading, ElNotification } from 'element-plus'
import 'element-plus/theme-chalk/el-loading.css'

// 拦截器: 蒙版Loading/token/修改配置

/**
 *  1.拦截器进行精细控制
 *    > 全局拦截器
 *    > 实例拦截器
 *    > 单次请求拦截器
 *
 *  2.响应结果的类型处理(泛型)
 */

const DEAFULT_LOADING = true

class HYRequest {
  instance: AxiosInstance
  loading?: LoadingInstance
  showLoading: boolean

  // request实例 => axios的实例
  constructor(config: HYRequestConfig) {
    this.instance = axios.create(config)
    this.showLoading = config.showLoading ?? DEAFULT_LOADING

    // 每个instance实例都添加拦截器
    this.instance.interceptors.request.use(
      (config) => {
        // 设置请求loading
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: '正在请求数据....',
            background: 'rgba(0, 0, 0, 0.5)'
          })
        }
        return config
      },
      (err) => {
        this.loading?.close()
        return err
      }
    )
    this.instance.interceptors.response.use(
      (res: any) => {
        this.loading?.close()
        const { data } = res
        const { code, msg } = data

        if (code === 200) return res
        if (code === 99) {
          Router.push({ path: '/account-failure', replace: true })
        }
        if (msg) {
          ElNotification({
            title: '提示',
            message: msg,
            type: 'error'
          })
        }

        return Promise.resolve(res)
      },
      (err) => {
        this.loading?.close()
        const { data } = err.response

        if (data.msg) {
          ElNotification({
            title: '提示',
            message: data.msg,
            type: 'error'
          })
        }

        if (err.code === 'ECONNABORTED') {
          ElNotification({
            title: '提示',
            message: '请求超时',
            type: 'error'
          })
        }

        return Promise.reject(err)
      }
    )

    // 针对特定的hyRequest实例添加拦截器
    this.instance.interceptors.request.use(
      config.interceptors?.requestSuccessFn,
      config.interceptors?.requestFailureFn
    )
    this.instance.interceptors.response.use(
      config.interceptors?.responseSuccessFn,
      config.interceptors?.responseFailureFn
    )
  }

  // 封装网络请求的方法
  request<T = any>(config: HYRequestConfig<T>) {
    // 单次请求的成功拦截处理
    if (config.interceptors?.requestSuccessFn) {
      config = config.interceptors.requestSuccessFn(config)
    }

    // 2.判断是否需要显示loading
    if (config.showLoading === false) {
      this.showLoading = config.showLoading
    }

    // 返回Promise
    return new Promise<T>((resolve, reject) => {
      this.instance
        .request<any, T>(config)
        .then((res) => {
          // 单次响应的成功拦截处理
          if (config.interceptors?.responseSuccessFn) {
            res = config.interceptors.responseSuccessFn(res)
          }

          // 2.将showLoading设置true, 这样不会影响下一个请求
          this.showLoading = DEAFULT_LOADING

          resolve(res)
        })
        .catch((err) => {
          // 1.将showLoading设置true, 这样不会影响下一个请求
          this.showLoading = DEAFULT_LOADING

          reject(err)
        })
    })
  }

  get<T = any>(config: HYRequestConfig<T> & ContentType) {
    return this.request({ ...config, method: 'GET' })
  }

  post<T = any>(config: HYRequestConfig<T> & ContentType) {
    return this.request({ ...config, method: 'POST' })
  }

  delete<T = any>(config: HYRequestConfig<T> & ContentType) {
    return this.request({ ...config, method: 'DELETE' })
  }

  patch<T = any>(config: HYRequestConfig<T> & ContentType) {
    return this.request({ ...config, method: 'PATCH' })
  }

  put<T = any>(config: HYRequestConfig<T> & ContentType) {
    return this.request({ ...config, method: 'PUT' })
  }
}

export default HYRequest
